package com.fyzk.activity.lottery.shuzicai.klpk;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.LinearLayout;

import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.lottery.shuzicai.BallInfo;
import com.fyzk.activity.lottery.shuzicai.TouZhuHelper;
import com.fyzk.activity.myview.WeiZhi;
import com.tyjc.lottery.R;
import com.fyzk.utils.LogUtil;
import com.fyzk.utils.ScreenUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanxs11 on 17/4/10.
 */

public class DrawBillView extends LinearLayout {

    private Context context;

	/* 屏幕中一行最多显示的球的个数（用来计算球的边长） */
//	private static final int h_max_count = 8;
    /**
     * 球的直径
     */
    private int ball_diameter;
    private int unitWidth;
    private int unitHeight;
    /**
     * 屏幕中一行需要显示的球的个数
     */
    private int h_show_count = 8;
    /* // 行之间的间距 */
    private int h_jianJu = 25;
    private boolean isJianJu;

    private Bitmap bitmap_ballsel;
    /* 小球未选中状态的图片 */
    private Bitmap bitmap_ballnormal;
    /* 选中状态下小球的字体颜色 */
    private int color_balltxt_sel;
    /* 未选中状态下小球的字体颜色 */
    private int color_balltxt_nor;

    /**
     * 球区与屏幕两边的间距
     */
    private int screen_margin = 20;
    /**
     * 球间距
     */
    private int ballMargin = 6;

    private Paint paint_ball;
    private TextPaint paint_txt;

    private int screen_width, screen_height, screen_DPI;
    private float screen_density;

    private boolean isXuanQiu = false;

    private List<BallInfo> list_qiu = new ArrayList<BallInfo>();

    /* 选球数  */
    private int select_count;
    /* 最大选球数  */
    private int select_max = 100;

    /**
     * 小球总个数
     */
    private int count;

    private String TAG = "SelectBallView";
    /**
     * 球类型 —— 红、蓝
     */
    private int ballType = 0;
    /* 关联选球控件*/
//	private SelectBallView guanLian_view;
    private List<DrawBillView> guanLian_views = new ArrayList();

    private int drawType = 0;   // 绘制类型（0：普通，6：对子，7：豹子，8：顺子，9：同花）

    private List<Integer> missValues = new ArrayList<>();
    private int maxMissValue = 0;
    /**
     * 遗漏值高度
     */
    private int missHeight = 0;
    /* 正常情况下遗漏值的颜色 */
    public int color_miss_nor;
    private boolean isShowMiss = true;

    public DrawBillView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
        this.context = context;
        init();
        initAttrValue(attrs);
    }

    public DrawBillView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        this.context = context;
        init();
        initAttrValue(attrs);
    }

    public DrawBillView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        this.context = context;
        init();
    }

    private void initAttrValue(AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs,
                R.styleable.SelectBallView);
        int N = typedArray.getIndexCount();
        int resourceId;
        for (int i = 0; i < N; i++) {
            int attr = typedArray.getIndex(i);
            switch (attr) {
                case R.styleable.SelectBallView_ball_nor:
                    resourceId = typedArray.getResourceId(
                            R.styleable.SelectBallView_ball_nor, 0);
                    bitmap_ballnormal = BitmapFactory.decodeResource(
                            context.getResources(), resourceId);
                    break;
                case R.styleable.SelectBallView_ball_sel:
                    resourceId = typedArray.getResourceId(
                            R.styleable.SelectBallView_ball_sel, 0);
                    bitmap_ballsel = BitmapFactory.decodeResource(
                            context.getResources(), resourceId);
                    break;
                case R.styleable.SelectBallView_lineNums:
                    resourceId = typedArray.getInt(
                            R.styleable.SelectBallView_lineNums, 8);
                    h_show_count = resourceId;
                    break;
                case R.styleable.SelectBallView_txtcolor_nor:
                    resourceId = typedArray.getColor(
                            R.styleable.SelectBallView_txtcolor_nor, 0x0);
                    color_balltxt_nor = resourceId;
                    break;
                case R.styleable.SelectBallView_txtcolor_sel:
                    resourceId = typedArray.getColor(
                            R.styleable.SelectBallView_txtcolor_sel, 0x0);
                    color_balltxt_sel = resourceId;
                    break;
                case R.styleable.SelectBallView_ballType:
                    resourceId = typedArray.getInt(
                            R.styleable.SelectBallView_ballType, 0x0);
                    ballType = resourceId;
                    break;
                case R.styleable.SelectBallView_jianJu:
                    isJianJu = typedArray.getBoolean(R.styleable.SelectBallView_jianJu, false);
                    break;
                case R.styleable.SelectBallView_isShowMiss:
                    isShowMiss = typedArray.getBoolean(R.styleable.SelectBallView_isShowMiss, true);
                    break;
//			case R.styleable.SelectBallView_margin:
//				resourceId = typedArray.getInt(
//						R.styleable.SelectBallView_margin, 6);
//				screen_margin = resourceId;
//				break;
            }
        }
        if (isJianJu) {
            screen_margin = screen_width / h_show_count / 4;
            ball_diameter = (screen_width - screen_margin * 2) / h_show_count;
            ballMargin = ball_diameter / 16;
        } else {
            ball_diameter = (screen_width - screen_margin * 2) / h_show_count;
        }
        unitWidth = ball_diameter;
        LogUtil.d("count:"+h_show_count+" unitWidth:"+unitWidth);
        unitHeight = ball_diameter * 3 / 2;

        color_miss_nor = Color.WHITE;
        if (isShowMiss) {
            missHeight = screen_width/16;
        } else {
            missHeight = 0;
        }
        invalidate();
    }

    private void init() {
        setWillNotDraw(false);
        if (isInEditMode()) {
            return;
        }
        // TODO Auto-generated method stub
        this.screen_width = ScreenUtils.getInstance().getWidth();
        this.screen_height = ScreenUtils.getInstance().getHeight();
        this.screen_DPI = ScreenUtils.getInstance().getDensityDPI();
        this.screen_density = ScreenUtils.getInstance().getDensity();
        ball_diameter = (screen_width - screen_margin * 2) / h_show_count;
        unitWidth = ball_diameter;
        unitHeight = ball_diameter * 3 / 2;
        setFocusable(true);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (paint_ball == null) {
            paint_ball = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint_ball.setColor(Color.BLACK);
            paint_ball.setAntiAlias(true);
            paint_ball.setTextSize(16 * screen_density);
            paint_ball.setTextAlign(Paint.Align.CENTER);
        }

        if (paint_txt == null) {
            paint_txt = new TextPaint(Paint.ANTI_ALIAS_FLAG);
            paint_ball.setAntiAlias(true);
            paint_txt.setTextSize(18 * screen_density);
            paint_txt.setTextAlign(Paint.Align.CENTER);
            Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
            paint_txt.setTypeface(font);
        }

        for (int i = 0; i < count; i++) {
            int left = 0;
            int right = 0;
            int top = 0;
            int bottom = 0;
            if (count % 2 == 1) {
                if (i < 6) {    // 第一行
                    left = (i % 6 + 1) * unitWidth + screen_margin;
                    right = left + unitWidth;
                    top = h_jianJu;
                    bottom = top + unitHeight;
                } else {
                    int indext = 0;

                    left = (int)(((i-6) % 7 + 0.5) * unitWidth) + screen_margin;
                    right = left + unitWidth;
                    top = unitHeight + h_jianJu * 2 + missHeight;
                    bottom = top + unitHeight;
                }
            } else {
                if (drawType == 9 || drawType == 10){ // 同花、同花顺
                    left = ((i+1) % h_show_count) * unitWidth + screen_margin;
                } else {
                    left = (i % h_show_count) * unitWidth + screen_margin;
                }
                right = left + unitWidth;
                top = (unitHeight + missHeight) * (i / h_show_count);
                bottom = top + unitHeight;
            }

            // 画球
            Rect rect;
            int moveY = 0;
            int textColor = 0;
            Bitmap bitmap;
            if (list_qiu.get(i).isSelected()) {
                moveY = -15;
                textColor = color_balltxt_sel;
                bitmap = bitmap_ballsel;
            } else {
                moveY = 0;
                textColor = color_balltxt_nor;
                bitmap = bitmap_ballnormal;
            }
            rect = new Rect(left + ballMargin, top + ballMargin + moveY + screen_margin, right - ballMargin, bottom
                    - ballMargin + moveY + screen_margin);
            list_qiu.get(i).rect_left = rect.left;
            list_qiu.get(i).rect_top = rect.top;
            list_qiu.get(i).rect_right = rect.right;
            list_qiu.get(i).rect_bottom = rect.bottom;

            paint_txt.setColor(textColor);
            canvas.drawBitmap(bitmap, null, rect, paint_ball);  // 绘制背景

            // 绘制桃花色
            int unitIconWH = rect.width()/5;
            int iconPadding = 5;
            int[] iconRs = {R.drawable.klpk_flower_1, R.drawable.klpk_flower_2, R.drawable.klpk_flower_3, R.drawable.klpk_flower_4};
            if (drawType == 9) {    // 同花
                Bitmap iconBitmap = BitmapFactory.decodeResource(
                        context.getResources(), iconRs[i]);
                Rect iconRect = new Rect(rect.left,rect.centerY()-rect.width()/2,rect.right,rect.centerY()+rect.width()/2);
                canvas.drawBitmap(iconBitmap, null, iconRect, paint_ball);
            } else if (drawType == 10) {    // 同花顺
                Bitmap iconBitmap = BitmapFactory.decodeResource(
                        context.getResources(), iconRs[i]);
                Rect iconRect = new Rect(rect.left,rect.top,rect.right,rect.top+rect.height()*2/3);
                Rect textRect = new Rect(rect.left,rect.bottom-rect.height()/2,rect.right,rect.bottom);
                canvas.drawBitmap(iconBitmap, null, iconRect, paint_ball);
                paint_txt.setColor(context.getResources().getColor(R.color.klpk_color_9f9f9f));
                drawText(canvas, paint_txt, "顺子", textRect, 20);
            } else {
                Bitmap iconBitmap = BitmapFactory.decodeResource(
                        context.getResources(), R.drawable.klpk_right_icon);
                int iconRight = rect.right - iconPadding;
                int iconBottom = rect.bottom - iconPadding*3;
                int iconLeft = iconRight - unitIconWH;
                int iconTop = iconBottom - (unitIconWH+2)*4;
                Rect rectIcon = new Rect(iconLeft, iconTop, iconRight, iconBottom);
                canvas.drawBitmap(iconBitmap, null, rectIcon, paint_ball);


                Rect textRect = new Rect(rect.left, rect.top, rect.right, rect.top+rect.height()/2);
                Rect textRect1 = new Rect(rect.left, rect.top, rect.right, rect.top+rect.height()/2);
                Rect textRect2 = new Rect(rect.left, rect.centerY()-rect.height()/4, rect.right, rect.centerY()+rect.height()/4);
                Rect textRect3 = new Rect(rect.left, rect.bottom-rect.height()/2, rect.right, rect.bottom);
                String text = list_qiu.get(i).getNum();
                switch (drawType) {
                    case 0:
                        text = getDrawText(text);
                        drawText(canvas, paint_txt, text, textRect, 20);
                        break;
                    case 6:     // 对子
                        text = getDrawText(text)+getDrawText(text);
                        drawText(canvas, paint_txt, text, textRect, 20);
                        break;
                    case 7:     // 豹子
                        text = getDrawText(text);
                        drawText(canvas, paint_txt, text, textRect1, 20);
                        drawText(canvas, paint_txt, text, textRect2, 14);
                        drawText(canvas, paint_txt, text, textRect3, 14);
                        break;
                    case 8:     // 顺子
                        int num = Integer.parseInt(text);
                        num = num%13 == 0 ? num : num%13;
                        String text1 = getDrawText((num%13 == 0 ? num : num%13)+"");
                        String text2 = getDrawText(((num+1)%13 == 0 ? (num+1) : (num+1)%13)+"");
                        String text3 = getDrawText(((num+2)%13 == 0 ? (num+2) : (num+2)%13)+"");
                        drawText(canvas, paint_txt, text1, textRect1, 20);
                        drawText(canvas, paint_txt, text2, textRect2, 14);
                        drawText(canvas, paint_txt, text3, textRect3, 14);
                        break;
                    default:

                        drawText(canvas, paint_txt, list_qiu.get(i), textRect);
                        break;
                }
            }

            if (isShowMiss) {
                // 遗漏
                Paint paintMiss = new Paint(Paint.ANTI_ALIAS_FLAG);
                paintMiss.setAntiAlias(true);
                paintMiss.setTextSize(12 * screen_density);
                paintMiss.setTextAlign(Paint.Align.CENTER);
                Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL);
                paintMiss.setTypeface(font);
                Rect missRect = new Rect(rect.left, rect.bottom-moveY, rect.right, rect.bottom + missHeight-moveY);
                String missValue = "--";
                if (missValues.size() == count) {
                    missValue = missValues.get(i)+"";
                    if (missValues.get(i) >= maxMissValue) {
                        paintMiss.setColor(Color.RED);
                    } else {
                        paintMiss.setColor(color_miss_nor);
                    }
                }

                drawText(canvas, paintMiss, missValue, missRect, 12);
            }
        }
    }

    /**
     * 触屏事件
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        select_count = getSelectedCount();
        int x, y;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                x = (int) event.getX();
                y = (int) event.getY();
                for (int i = 0; i < list_qiu.size(); i++) {
                    Rect r = new Rect(list_qiu.get(i).rect_left, list_qiu.get(i).rect_top,
                            list_qiu.get(i).rect_right
                            , list_qiu.get(i).rect_bottom);
                    if (r.contains(x, y)) {
                        isXuanQiu = true;
                        WeiZhi w = new WeiZhi(r.left, r.right, r.top, r.bottom, x,
                                y, list_qiu.get(i).getNum());
                        w.setType(ballType);
                        w.isShowMoveBall = true;
                        TouZhuHelper.getInstance().ballClick(w);
                        break;
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                // int what = WHAT_UP;
                x = (int) event.getX();
                y = (int) event.getY();
                if (isXuanQiu) {
                    for (int i = 0; i < list_qiu.size(); i++) {
                        BallInfo info = list_qiu.get(i);
                        Rect r = new Rect(info.rect_left, info.rect_top, info.rect_right
                                , info.rect_bottom);
                        if (r.contains(x, y)) {

                            if (info.isSelected()) {
                                select_count--;
                                info.setSelected(false);
                            } else {
                                select_count++;
                                if (select_count > select_max) {
                                    select_count--;
                                    AppToast.getToast().show("最多可选" + select_max + "个球");
                                } else {
                                    for (DrawBillView guanLian_view : guanLian_views) {

                                        if (guanLian_view != null && guanLian_view
                                                .getBallInfoList().get(i).isSelected()) {
                                            guanLian_view.getBallInfoList().get(i).setSelected
                                                    (false);
                                            guanLian_view.setSelect_count(guanLian_view
                                                    .getSelect_count() - 1);
                                            guanLian_view.invalidate();
                                        }
                                    }
                                    info.setSelected(true);
                                }
                            }
                        }
                    }
                }
                isXuanQiu = false;
                WeiZhi w = new WeiZhi();
                w.isShowMoveBall = false;

                TouZhuHelper.getInstance().ballClick();
                TouZhuHelper.getInstance().ballClick(w);
                this.invalidate();
                // WeiZhi w = new WeiZhi();
                // sendMessage(what, w);
                break;
        }
        return true;
    }

    public void setBallInfoList(List<BallInfo> list_qiu) {
        this.list_qiu = list_qiu;
        count = this.list_qiu.size();
        select_count = 0;
        for (int i = 0; i < list_qiu.size(); i++) {
            if (list_qiu.get(i).isSelected()) {
                select_count++;
            }
            list_qiu.get(i).type = ballType;
        }
        invalidate();// 更新界面
    }

    public void setBallInfoList(List<BallInfo> list_qiu, int count) {
        this.list_qiu = list_qiu;
        this.count = count;
        select_count = 0;
        for (int i = 0; i < list_qiu.size(); i++) {
            if (list_qiu.get(i).isSelected()) {
                select_count++;
            }
            list_qiu.get(i).type = ballType;
        }
        invalidate();// 更新界面
    }

    private int getSelectedCount() {
        int sel = 0;

        for (BallInfo info : this.list_qiu) {
            if (info.isSelected()) {
                sel++;
            }
        }
        return sel;
    }


    public List<BallInfo> getBallInfoList() {
        return this.list_qiu;
    }

    @Override
    public void invalidate() {
        // TODO Auto-generated method stub
        super.invalidate();
    }

    /**
     * 绘制文字
     *
     * @param canvas
     * @param paint
     * @param info
     * @param rect
     */
    private void drawText(Canvas canvas, Paint paint, BallInfo info, Rect rect) {

        String text = info.getNum();
        switch (drawType) {
            case 0:
                text = getDrawText(text);
                break;
            case 6:     // 对子
                text = getDrawText(text)+getDrawText(text);
                break;
            case 7:     // 豹子
                text = getDrawText(text)+getDrawText(text)+getDrawText(text);
                break;
            case 8:     // 顺子
                int num = Integer.parseInt(info.getNum());
                num = num%13 == 0 ? num : num%13;
                text = getDrawText((num%13 == 0 ? num : num%13)+"")+"\n"+
                        getDrawText(((num+1)%13 == 0 ? (num+1) : (num+1)%13)+"")+"\n"+
                        getDrawText(((num+2)%13 == 0 ? (num+2) : (num+2)%13)+"")+"\n";
                break;
        }
        drawText(canvas, paint, text, rect, 20);
    }

    /**
     * 绘制文字
     *
     * @param canvas
     * @param paint
     * @param text
     * @param rect
     */
    private void drawText(Canvas canvas, Paint paint, String text, Rect rect, int size) {

        paint.setTextSize(size * screen_density);
        Paint.FontMetrics fm = paint.getFontMetrics();
        int baseLine = (int) (rect.top
                + (rect.bottom - rect.top - fm.bottom + fm.top) / 2 - fm.top);

        canvas.drawText(text, rect.centerX(), baseLine, paint);
    }

    private String getDrawText(String text) {
        if (text.equals("1")) {
            text = "A";
        } else if (text.equals("11")) {
            text = "J";
        } else if (text.equals("12")) {
            text = "Q";
        } else if (text.equals("13")) {
            text = "K";
        } else {
            text = text;
        }
        return text;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = this.screen_width;
        int height = (count / h_show_count) * (unitHeight + h_jianJu + missHeight) + h_jianJu;
        if (count % h_show_count != 0) {
            height = (count / h_show_count + 1) * (unitHeight + h_jianJu + missHeight) + h_jianJu + screen_margin;
        }
        setMeasuredDimension(width, height);
    }

    public int getSelect_max() {
        return select_max;
    }

    public void setSelect_max(int select_max) {
        this.select_max = select_max;
    }


    public void setGuanLian_view(DrawBillView guanLian_view) {
        this.guanLian_views.clear();
        this.guanLian_views.add(guanLian_view);
    }

    public void setGuanLian_view(List<DrawBillView> guanLian_views) {
        this.guanLian_views.clear();
        this.guanLian_views.addAll(guanLian_views);
    }

    public int getSelect_count() {
        return select_count;
    }

    public void setSelect_count(int select_count) {
        this.select_count = select_count;
    }

    public void setDrawType(int drawType) {
        this.drawType = drawType;
    }

    public int getH_show_count() {
        return h_show_count;
    }

    public void setH_show_count(int h_show_count) {
        this.h_show_count = h_show_count;
        if (isJianJu) {
            screen_margin = screen_width / h_show_count / 4;
            ball_diameter = (screen_width - screen_margin * 2) / h_show_count;
            ballMargin = ball_diameter / 16;
        } else {
            ball_diameter = (screen_width - screen_margin * 2) / h_show_count;
        }
        unitWidth = ball_diameter;
        unitHeight = ball_diameter * 3 / 2;
        invalidate();
    }

    public void setMissValues(List<Integer> missValues) {
        this.missValues = missValues;
        maxMissValue = 0;
        for (int i =0; i < missValues.size(); i++) {
            if (maxMissValue < missValues.get(i)) {
                maxMissValue = missValues.get(i);
            }
        }
        invalidate();
    }
}
